/*
 * MainView.java
 *
 * Created on __DATE__, __TIME__
 */

package pl.streamsoft.test.currency_view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JComboBox;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;

import net.sourceforge.jdatepicker.JDateComponentFactory;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import pl.streamsoft.test.currency_buisness.CurrenciesService;
import pl.streamsoft.test.currency_buisness.dto.CurrencyDTO;
import pl.streamsoft.test.currency_buisness.dto.CurrencyTypeDTO;
import pl.streamsoft.test.currency_buisness.exceptions.ServiceException;
import pl.streamsoft.test.currency_view.helpers.DateHelper;
import pl.streamsoft.test.currency_view.storage.CurrencyTableModel;
import pl.streamsoft.test.currency_view.storage.CurrencyTypeComboboxModel;
import pl.streamsoft.test.currency_view.storage.Signal;
import pl.streamsoft.test.currency_view.storage.Storage;

/**
 * 
 * @author __USER__
 */
public class MainView extends ApplicationView implements Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7229089124063727286L;

	/** Creates new form MainView */
	public MainView() {
		initComponents();
	}

	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		currenciesTable = new javax.swing.JTable(Storage.getInstance()
				.getCurrencyTableModel());
		jToolBar1 = new javax.swing.JToolBar();
		showButton = new javax.swing.JButton();
		addButton = new javax.swing.JButton();
		editButton = new javax.swing.JButton();
		deleteButton = new javax.swing.JButton();
		jSeparator1 = new javax.swing.JToolBar.Separator();
		downloadButton = new javax.swing.JButton();
		jPanel1 = new javax.swing.JPanel();
		jLabel1 = new javax.swing.JLabel();
		currencyTypeComboBox = new javax.swing.JComboBox<CurrencyTypeDTO>(
				Storage.getInstance().getCurrencyTypeComboboxModel());
		dateFromTextField = (JDatePickerImpl) JDateComponentFactory
				.createJDatePicker();
		dateToTextField = (JDatePickerImpl) JDateComponentFactory
				.createJDatePicker();
		jLabel3 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		currenciesTable
				.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
		currenciesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		currencyTypeComboBox.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				updateCurrencies();
				Storage.getInstance().averageUpdateSignal.execute();

			}
		});
		jScrollPane1.setViewportView(currenciesTable);

		jToolBar1.setBackground(new java.awt.Color(204, 204, 204));
		jToolBar1.setRollover(true);
		jToolBar1.setFloatable(false);

		showButton.setBackground(new java.awt.Color(204, 204, 204));
		showButton.setText("Poka\u017c");
		showButton.setFocusable(false);
		showButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		showButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		showButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				showButtonAction(evt);
			}
		});
		jToolBar1.add(showButton);

		addButton.setBackground(new java.awt.Color(204, 204, 204));
		addButton.setText("Dodaj");
		addButton.setFocusable(false);
		addButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		addButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		addButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				addButtonAction(evt);
			}
		});
		jToolBar1.add(addButton);

		editButton.setBackground(new java.awt.Color(204, 204, 204));
		editButton.setText("Popraw");
		editButton.setFocusable(false);
		editButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		editButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		editButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				editButtonAction(evt);
			}
		});
		jToolBar1.add(editButton);

		deleteButton.setBackground(new java.awt.Color(204, 204, 204));
		deleteButton.setText("Usu\u0144");
		deleteButton.setFocusable(false);
		deleteButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
		deleteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		deleteButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				deleteButtonAction(evt);
			}
		});
		jToolBar1.add(deleteButton);
		jToolBar1.add(jSeparator1);

		downloadButton.setBackground(new java.awt.Color(204, 204, 204));
		downloadButton.setText("Pobierz");
		downloadButton.setFocusable(false);
		downloadButton.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
		downloadButton
				.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
		downloadButton
				.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
		downloadButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				downloadButtonAction(evt);
			}
		});
		jToolBar1.add(downloadButton);

		jLabel1.setText("Waluta");
		jLabel3.setText("Do");
		jLabel2.setText("Od");

		dateFromTextField.getModel().setSelected(true);
		dateToTextField.getModel().setSelected(true);

		dateFromTextField.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				updateCurrencies();
				Storage.getInstance().averageUpdateSignal.execute();

			}
		});

		dateToTextField.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				updateCurrencies();
				Storage.getInstance().averageUpdateSignal.execute();

			}
		});

		Storage.getInstance().averageUpdateSignal.addObserver(this);
		Storage.getInstance().newCurrencyAddedSignal.addObserver(this);

		org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout
				.setHorizontalGroup(jPanel1Layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(org.jdesktop.layout.GroupLayout.TRAILING,
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.add(jPanel1Layout
												.createParallelGroup(
														org.jdesktop.layout.GroupLayout.LEADING)
												.add(jPanel1Layout
														.createSequentialGroup()
														.add(jLabel1)
														.add(10, 10, 10)
														.add(currencyTypeComboBox,
																0, 108,
																Short.MAX_VALUE))
												.add(jPanel1Layout
														.createSequentialGroup()
														.add(jPanel1Layout
																.createParallelGroup(
																		org.jdesktop.layout.GroupLayout.LEADING)
																.add(jLabel2)
																.add(jLabel3))
														.addPreferredGap(
																org.jdesktop.layout.LayoutStyle.RELATED)
														.add(jPanel1Layout
																.createParallelGroup(
																		org.jdesktop.layout.GroupLayout.LEADING)
																.add(dateFromTextField,
																		org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																		134,
																		Short.MAX_VALUE)
																.add(dateToTextField,
																		org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																		134,
																		Short.MAX_VALUE))))
										.addContainerGap()));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(jPanel1Layout
								.createSequentialGroup()
								.add(jPanel1Layout
										.createParallelGroup(
												org.jdesktop.layout.GroupLayout.BASELINE)
										.add(jLabel1)
										.add(currencyTypeComboBox,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										org.jdesktop.layout.LayoutStyle.RELATED)
								.add(jPanel1Layout
										.createParallelGroup(
												org.jdesktop.layout.GroupLayout.BASELINE)
										.add(jLabel2)
										.add(dateFromTextField,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										org.jdesktop.layout.LayoutStyle.RELATED)
								.add(jPanel1Layout
										.createParallelGroup(
												org.jdesktop.layout.GroupLayout.BASELINE)
										.add(jLabel3)
										.add(dateToTextField,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
								.addContainerGap(67, Short.MAX_VALUE)));

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(layout
						.createSequentialGroup()
						.add(jPanel1,
								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED)
						.add(jScrollPane1,
								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
								627, Short.MAX_VALUE).addContainerGap())
				.add(jToolBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
						825, Short.MAX_VALUE));
		layout.setVerticalGroup(layout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(org.jdesktop.layout.GroupLayout.TRAILING,
						layout.createSequentialGroup()
								.add(jToolBar1,
										org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
										46,
										org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										org.jdesktop.layout.LayoutStyle.RELATED)
								.add(layout
										.createParallelGroup(
												org.jdesktop.layout.GroupLayout.LEADING)
										.add(jPanel1,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.add(jScrollPane1,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												392, Short.MAX_VALUE))
								.addContainerGap()));

		pack();

		updateCurrenciesTypesList();
		updateCurrencies();

	}// </editor-fold>
		// GEN-END:initComponents

	protected void updateCurrenciesTypesList() {
		CurrenciesService controller = new CurrenciesService();
		try {
			List<CurrencyTypeDTO> currencyTypesList = controller
					.getCurrenciesTypes();
			CurrencyTypeComboboxModel model = (CurrencyTypeComboboxModel) currencyTypeComboBox
					.getModel();
			model.replaceElementsWith(currencyTypesList);
		} catch (ServiceException e) {
			showError("DAOException", e.getMessage());
			e.printStackTrace();
		}
	}

	protected void updateAverage() {
		try {
			CurrenciesService service = new CurrenciesService();
			CurrencyTypeDTO dto = new CurrencyTypeDTO();
			dto.acronym = getCurrencyAcronym();
			setTitle(getCurrencyAcronym() + " Average is "
					+ service.getAverage(dto));
			this.repaint();

		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}

	protected void updateCurrencies() {
		try {
			CurrencyTableModel model = Storage.getInstance()
					.getCurrencyTableModel();
			model.updateFromService(getFromDate(), getToDate(),
					getCurrencyAcronym());
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}

	private void downloadButtonAction(java.awt.event.ActionEvent evt) {
		DownloadView downloadView = new DownloadView(this, true);
		downloadView.setVisible(true);
	}

	private void deleteButtonAction(java.awt.event.ActionEvent evt) {
		CurrencyDTO item = getSelectedItem();
		if (item != null) {
			if (confirmDialog("Deleting", "Are you sure?")) {
				try {
					CurrenciesService controller = new CurrenciesService();
					controller.delete(item);
					updateCurrencies();
					Storage.getInstance().averageUpdateSignal.execute();
				} catch (ServiceException e) {
					e.printStackTrace();
				}
			}
		} else {
			showWarning("Pokaż element", "Nie wybrano elementu");
		}

	}

	private void editButtonAction(java.awt.event.ActionEvent evt) {
		ItemView itemView = new ItemView(this, true);
		CurrencyDTO item = getSelectedItem();
		if (item != null) {
			itemView.setDTO(item);

			itemView.changeMode(ItemView.VIEW_MODE_EDITION);
			itemView.setVisible(true);
		} else {
			showWarning("Pokaż element", "Nie wybrano elementu");
		}
	}

	private void addButtonAction(java.awt.event.ActionEvent evt) {
		ItemView itemView = new ItemView(this, true);
		itemView.changeMode(ItemView.VIEW_MODE_CREATING);
		itemView.setVisible(true);

	}

	private void showButtonAction(java.awt.event.ActionEvent evt) {
		ItemView itemView = new ItemView(this, true);
		CurrencyDTO item = getSelectedItem();
		if (item != null) {
			itemView.setDTO(item);
			itemView.changeMode(ItemView.VIEW_MODE_VIEWING);
			itemView.setVisible(true);
		} else {
			showWarning("Pokaż element", "Nie wybrano elementu");
		}
	}

	public CurrencyDTO getSelectedItem() {
		ListSelectionModel listSelectionModel = currenciesTable
				.getSelectionModel();

		if (!listSelectionModel.isSelectionEmpty()) {
			int selectedIndex = listSelectionModel.getLeadSelectionIndex();
			CurrencyTableModel model = (CurrencyTableModel) currenciesTable
					.getModel();
			return model.getValueAt(selectedIndex);
		}
		return null;
	}

	public Date getFromDate() {
		if (dateFromTextField.getModel().isSelected()) {
			return DateHelper.getDate(dateFromTextField);
		} else {
			return new Date();
		}
	}

	public Date getToDate() {
		if (dateToTextField.getModel().isSelected()) {
			return DateHelper.getDate(dateToTextField);
		} else {
			return new Date();
		}
	}

	public String getCurrencyAcronym() {
		CurrencyTypeDTO item = (CurrencyTypeDTO) currencyTypeComboBox
				.getSelectedItem();
		if (item != null) {
			return item.acronym;
		} else {
			return "";
		}

	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					for (LookAndFeelInfo info : UIManager
							.getInstalledLookAndFeels()) {
						if ("Nimbus".equals(info.getName())) {
							UIManager.setLookAndFeel(info.getClassName());
							break;
						}
					}
				} catch (UnsupportedLookAndFeelException e) {
				} catch (ClassNotFoundException e) {
				} catch (InstantiationException e) {
				} catch (IllegalAccessException e) {
				}
				new MainView().setVisible(true);
			}
		});
	}

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton showButton;
	private javax.swing.JButton addButton;
	private javax.swing.JButton editButton;
	private javax.swing.JButton deleteButton;
	private javax.swing.JButton downloadButton;
	private JComboBox<CurrencyTypeDTO> currencyTypeComboBox;
	private JDatePickerImpl dateFromTextField;
	private JDatePickerImpl dateToTextField;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JToolBar.Separator jSeparator1;
	private javax.swing.JTable currenciesTable;
	private javax.swing.JToolBar jToolBar1;

	// End of variables declaration//GEN-END:variables

	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof Signal) {
			Signal property = (Signal) o;

			if (property.getName().equals("mainTitle")) {
				updateAverage();
			} else if (property.getName().equals("newCurrencyAdded")) {
				updateCurrenciesTypesList();
			}
		}
	}
}